package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.ruoyi.common.config.BigDataConfig;
import com.ruoyi.common.core.domain.JSONObjectPro;
import com.ruoyi.common.core.page.Page;
import com.ruoyi.common.exception.BigDataException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SnowFlakeIDGenerator;
import com.ruoyi.common.utils.http.BigDataResponse;
import com.ruoyi.common.utils.http.CommonResponse;
import com.ruoyi.common.utils.http.HttpRequest;
import com.ruoyi.system.domain.request.realtimevideo.HistoryVideoParam;
import com.ruoyi.system.domain.vo.realtimevideo.DeviceVideo;
import com.ruoyi.system.domain.vo.common.ComDvoName;
import com.ruoyi.system.domain.request.realtimevideo.ServerVideo;
import com.ruoyi.system.service.IEquipmentManagementService;
import com.ruoyi.system.service.IRealtimeVideoService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 描述 实时视频Service实现类
 * 作者 ZhangPing
 * 创建时间 2023/8/21 17:22
 */
@Service
public class RealtimeVideoServiceImpl implements IRealtimeVideoService {

    @Autowired
    private BigDataConfig bigDataConfig;
    @Autowired
    private IEquipmentManagementService equipmentManagementService;

    /**
     * 服务器历史视频列表
     * @param params
     * @return
     */
    public Object serverHistoryList(HistoryVideoParam params){
        JSONObjectPro bigDataParam = new JSONObjectPro()
                .put("pageIndex", params.getPageNum())
                .put("pageSize", params.getPageSize())
                .put("startTime", params.getStartTime())
                .put("endTime", params.getEndTime())
                .put("dvoList", Collections.singletonList(params.getDeviceId()))
                .put("channelList", Collections.singletonList(params.getChannel()))
                .put("streamTypeList", Collections.singletonList(params.getMediaType()));
        BigDataResponse<List<ServerVideo>> response = HttpRequest.postJsonBigData(bigDataConfig.getApiUrl() + "/videoHisMedia/queryHisMediaList", bigDataParam, new TypeReference<List<ServerVideo>>(){}.getType());
        if (!response.isSuccess()) throw new BigDataException();
        List<ServerVideo> data = response.getData();
        if (ObjectUtils.isNotEmpty(data)){
            //添加公司名称和设备名称
            List<ComDvoName> queryMap = equipmentManagementService.selectDeviceAndCompanyName(Collections.singletonList(params.getDeviceId()));
            ComDvoName info = queryMap.get(0);
            data.stream().forEach(i -> {
                i.setCompanyName(info.getCompanyName()).setNumberPlate(info.getNumberPlate());
            });
        }
        return new JSONObjectPro()
                .put("total", response.getTotalCount())
                .put("list", data);
    }

    /**
     * 设备历史视频列表
     * @param params
     * @return
     */
    public Page<ServerVideo> deviceHistoryList(HistoryVideoParam params){
        long offsetTime = DateUtils.parseDate(params.getStartTime()).getTime() - DateUtils.parseDate(params.getEndTime()).getTime();
        if(offsetTime > 24 * 60 * 60 * 1000) throw new ServiceException("时间范围不能超过一天");
        JSONObjectPro bigDataParam = new JSONObjectPro()
                .put("pagenumber",params.getPageNum())
                .put("pagesize", params.getPageSize())
                .put("requestId", SnowFlakeIDGenerator.getInstance().nextId())
                .put("devNo", params.getDeviceId())
                .put("distributeTime", DateUtils.getTime())
                .put("beginTime", params.getStartTime())
                .put("endTime", params.getEndTime())
                .put("chanelId", params.getChannel())
                .put("mediaType", params.getMediaType())
                .put("storageType", params.getStorageType())
                .put("codeType", params.getCodeType())
                .put("response", true)
                .put("distributeMsgTopic", "QueryMediaList_Send");
        CommonResponse<JSONObject> response = HttpRequest.postJson(bigDataConfig.getGatewayApiUrl() + "/KafkaApiController/queryMediaListPaging", new JSONObjectPro()
                .put("id", params.getTagId())
                .put("content", bigDataParam.toJSONString()), JSONObject.class);
        if (!response.isSuccess()) throw new BigDataException();
        JSONObject resultJson = response.getData().getJSONObject("result");
        int total = resultJson.getIntValue("mediafiletotal");
        List<DeviceVideo> videoList = resultJson.getList("mediaListItems", DeviceVideo.class);
        //添加公司名称和设备名称
        List<ComDvoName> queryMap = equipmentManagementService.selectDeviceAndCompanyName(Collections.singletonList(params.getDeviceId()));
        ComDvoName info = queryMap.get(0);
        List<ServerVideo> resultList = videoList.stream().map(i -> {
            ServerVideo serverVideo = new ServerVideo()
                    .setCompanyName(info.getCompanyName())
                    .setDvo(info.getDeviceId())
                    .setNumberPlate(info.getNumberPlate())
                    .setChannel(i.getChanelId())
                    .setStreamType(i.getMediaType())
                    .setFileSize(i.getFileSize())
                    .setStartTime(DateUtils.parseDateTime(new Date(i.getStartTime())))
                    .setEndTime(DateUtils.parseDateTime(new Date(i.getEndTime())));
            return serverVideo;
        }).collect(Collectors.toList());
        return new Page<>(total, resultList);
    }
}
